package com.bjsxt.shop.head.springmvc.intercepto;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.common.util.ConstatFinalUtil;
import com.bjsxt.shop.goods.pojo.AUsersCar;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.users.pojo.AUsers;
import com.bjsxt.shop.users.service.IUsersShopService;
/**
 * 拦截器
 * @author Administrator
 *
 */
@Component("authInter")
public class AuthInter extends HandlerInterceptorAdapter
{
	@Resource
	private IUsersShopService usersShopService;
	@Resource
	private IGoodsService goodsService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		ConstatFinalUtil.SYS_LOGGER.info("--preHandle--");
        HttpSession session = request.getSession() ; 
		
		AUsers users = (AUsers) session.getAttribute("users");
		if(users != null)
		{
			return true ; 
		}
		if("0".equalsIgnoreCase(ConstatFinalUtil.CONFIG_JSON.getString("version")))
		{
			/* 查询id为1的用户 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", "1");
			users = this.usersShopService.findOneUsersService(condMap);
			session.setAttribute("users", users);
			
			/* 在这合并数据 */
			this.updateMerageUsersCar(request,response,users);
			return true ; 
		}
		return false;
	}
	/**
	 * 合并数据
	 * 
	 * ~获取Cookie里面购物车的信息
	 * ~循环购物车,
	 * ~入库,入库的时候要判断是否存在,如果存在,加数量;如果不存在,直接添加吧
	 * ~清空Cookie
	 */
	private void updateMerageUsersCar(HttpServletRequest request,HttpServletResponse response,AUsers users)
	{
		JSONArray goodsArr=new JSONArray();
		Cookie[] cookies=request.getCookies();
		for (int i = 0; i < cookies.length; i++)
		{
			Cookie cookie=cookies[i];
			if("goodsCarList".equalsIgnoreCase(cookie.getName()))
			{
				goodsArr=(JSONArray) JSON.parse(cookie.getValue());
				/*~清空Cookie*/
				cookie.setValue("");
				cookie.setPath(request.getContextPath());
				cookie.setMaxAge(0);
				response.addCookie(cookie);
			}
		}
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		/*~循环购物车,
		 * goodsArr绝对不是null,不会报空指针
		 * */
		for (Iterator iterator = goodsArr.iterator(); iterator.hasNext();)
		{
			JSONObject goodsJSON = (JSONObject) iterator.next();
			String gid=goodsJSON.get("id")+"";
			String num=goodsJSON.get("num")+"";
			/*
			 * ~入库,入库的时候要判断是否存在,如果存在,加数量;如果不存在,直接添加吧
			 * 
			 * 按照用户id和商品id一块查询
			 * */
			condMap.put("goodsId", gid);
			condMap.put("usersId", users.getId());
			AUsersCar usersCar=this.goodsService.findOneUsersCarService(condMap);
			
			/*
			 * 断言
			 * */
			boolean update = true ; 
			if(usersCar==null)
			{
				usersCar = new AUsersCar() ;
				usersCar.setUsersId(users.getId());
				usersCar.setCreateTime(new Date());
				usersCar.setNum(Integer.valueOf(num));
				
				update = false ; 
			}else
			{
				usersCar.setNum(usersCar.getNum() + Integer.valueOf(num));
			}
			usersCar.setGoodsId(Integer.valueOf(gid));
			usersCar.setStatus(Byte.valueOf("1"));
			usersCar.setUpdateTime(new Date());
			usersCar.setPubTime(new Date());
			
			JSONObject resDBJSON = null ; 
			if(update)
			{
				resDBJSON = this.goodsService.updateOneUsersCarService(usersCar);
			}else
			{
				resDBJSON = this.goodsService.saveOneUsersCarService(usersCar);
			}
			ConstatFinalUtil.SYS_LOGGER.info("结果:{}",resDBJSON);
		}
		
	}
	
}
